import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Box, Button, Dialog, Drawer, Icon, Message, Tree } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { column } from './stores/definitions';
import RegionGroupForm from './components/RegionGroupForm';
import { useHistory } from 'react-router';
import RegionForm from '../Region/components/RegionForm';

const TreeNode = Tree.Node;

const RegionGroup = () => {
  return (
    <TauPage className="page-container-2">
      <GroupList />
      <RegionList />
    </TauPage>

  );
};

const GroupList = observer(() => {
  const history = useHistory();
  const { ccStationGroupStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const objRef = useRef();

  useEffect(() => {
    (async () => {
      await store.fetchGroups();
    })();
  }, []);

  const handleSelected = (v) => {
    if (!v.length) return;
    store.selectedName = v[0];
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    objRef.current = {};
    setModal(['add']);
  };

  // 点击打开编辑
  const handleOpenEdit = () => {
    objRef.current = store.selected;
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 删除数据提交
  const handleRemove = () => {
    Dialog.confirm({
      content: t`删除【${store.selected.name}】吗？`,
      onOk: () => store.remove({ ...store.selected, originName: store.selected.name, regions: [] }),
    });
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(toJS(result));
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  function renderNode(item) {
    const isLeaf = !item.children?.length;
    const isCity = item.fullId;
    const iconType = isCity ? 'icon-city' : 'icon-region-group';
    return (
      <TreeNode
        key={item.name}
        label={item.name}
        icon={<i className={`iconfont ${iconType}`} />}
        isLeaf={isLeaf}
        data={item}
        selectable={!isCity}
      >
        {item.children?.map((c) => renderNode(c))}
      </TreeNode>
    );
  }

  return (
    <div className="left-panel" style={{ maxWidth: 240, minWidth: 240, padding: 10, borderRight: 'solid 1px var(--color-fill1-4)' }}>
      <Box direction="row" align="center" style={{ margin: '0 0 12px 0' }}>
        <Button type="normal" onClick={() => { history.goBack(); }} style={{ marginLeft: '-10px', border: 0 }}>
          <Icon type="arrow-left" style={{ padding: 6, border: '1px solid #ccc', borderRadius: '50%', color: 'var(--btn-pure-primary-bg)' }} />
        </Button>
        <span>{t`区域分组`}</span>
      </Box>
      <Button.Group style={{ display: 'flex', justifyContent: 'center', marginBottom: 10 }}>
        <Button type="primary" onClick={handleOpenAdd}>{t`添加`}</Button>
        <Button type="normal" onClick={handleOpenEdit} disabled={!store.selected} >{t`编辑`}</Button>
        <Button type="normal" onClick={handleRemove} disabled={!store.selected} >{t`删除`}</Button>
      </Button.Group>

      {store.cities.length &&
        <Tree
          isNodeBlock={{ indent: 10 }}
          style={{ width: '100%' }}
          selectedKeys={[store.selected?.name]}
          onSelect={handleSelected}
          expandedKeys={toJS(store.cities).map((c) => c.name)}
        >
          <TreeNode
            key="root"
            label={t`所有分组`}
            isLeaf={false}
            selectable={false}
          >
            {toJS(store.cities)?.filter((c) => c.children.length > 0).map((item) => renderNode(item))}
          </TreeNode>
        </Tree>}
      <Drawer
        visible={!!modal[0]}
        title={modal[0] === 'add' ? t`添加城市` : t`修改城市【${objRef.current?.name}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="700px"
      >
        <RegionGroupForm
          groupName={objRef.current?.name}
          parentId={undefined}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
    </div>
  );
});

const RegionList = observer(() => {
  const { ccStationGroupStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const objRef = useRef();

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { ...searchArgs } = params.values;
    store.search = {
      ...searchArgs,
    };
  };

  // 点击打开查看
  const handleOpenView = (station) => {
    objRef.current = station;
    setModal(['view']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 线路更新
  const handlePriceUpdate = async () => {
    try {
      await store.updateGroup();
      Message.success({ content: t`线路更新成功` });
    } catch (error) {
      console.log('🚀 _ file: index.jsx:195 _ error:', error);
      Message.success({ content: t`线路更新失败` });
    }
  };

  return (
    <div className="main-content" >
      <TauActionPanel
        actions={[
          {
            name: 'btn-priceUpdate',
            title: t`线路更新`,
            type: 'primary',
            onClick: handlePriceUpdate,
          },
        ]}
        className="action-panel"
        onSearch={handleOnSearch}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
      />
      <div className="content">
        <TauTable
          primaryKey="itemId"
          tableLayout="fixed"
          loading={store.loading}
          dataSource={toJS(store.regions)}
          hidePagination
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('itemId', { width: 88, cell: (v, _, region) => <Button type="primary" text onClick={() => handleOpenView(region)}>{v}</Button> }),
            column('name', {}),
            column('disabled', {}),
            column('sortWeight', { width: 88 }),
            column('ts', {}),
          ]}
        />
      </div>
      <Drawer
        visible={!!modal[0]}
        title={modal[0] === 'add' ? t`添加区域` : t`修改区域【${objRef.current?.name}】`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="700px"
      >
        <RegionForm
          regionId={objRef.current?.itemId}
          parentId={objRef.current?.parentId}
          modal={modal}
          onCancel={handleCancel}
        />
      </Drawer>
    </div>
  );
});

export default observer(RegionGroup);
